<template>
    <view class="container">
        <div class="border">
            <div class="card">
                <div style="height: 10px"></div>
                <div class="card-top">
                    <div style=" text-align: center;font-size: 18px;font-weight: 500;">基础信息</div>
                </div>
                <div style="height: 10px"></div>
                <u-line color="#83AF92"></u-line>
                <div style="height: 15px;"></div>
                <div class="newFlex">
                    <div>收运地点</div>
                    <div>{{ farmName }}</div>
                </div>
                <div style="height: 15px;"></div>
                <div class="newFlex">
                    <div>收运车辆</div>
                    <div>{{ licenseNumber }}</div>
                </div>
                <div style="height: 15px;"></div>
                <div class="newFlex">
                    <div>有机质类型</div>
                    <div>{{ vehicleOrganicType }}</div>
                </div>
                <div style="height: 15px;"></div>
                <div class="lookBtn" v-if="flag == '进行中任务'" @click="taskDetail(item)">查看</div>
            </div>
            <div style="height: 10px;"></div>
            <div class="card">
                <div style="height: 10px"></div>
                <div class="card-top">
                    <div style=" text-align: center;font-size: 18px;font-weight: 500;">上报信息</div>
                </div>
                <div style="height: 10px"></div>
                <u-line color="#83AF92"></u-line>
                <div style="height: 15px;"></div>
                <div style="width: 90%;margin-left: 5%;">
                    <div>
                        <div>收集数量（吨）</div>
                        <div style="height: 15rpx;"></div>
                        <div class="borders">
                            <input type="number" style="height: 42px;" placeholder-class="holder-class"
                                placeholder="请输入" v-model="estimatedWeight">
                        </div>
                    </div>
                    <div style="height: 15px;"></div>
                    <div>
                        <div>检测浓度（TS）</div>
                        <div style="height: 15rpx;"></div>
                        <div class="borders">
                            <input type="text" style="height: 42px;" placeholder-class="holder-class"
                                v-model="organicConcentration" placeholder="请输入浓度">
                        </div>
                    </div>
                    <div style="height: 15px;"></div>
                    <div>
                        <div>现场照片（图1）</div>
                        <div style="height: 15rpx;"></div>
                        <!-- <div class="borders"> -->
                        <u-upload :capture="['camera']" :fileList="fileList1" @afterRead="afterRead" @delete="deletePic"
                            name="1" multiple :maxCount="1" width="150" height="150">
                        </u-upload>
                        <!-- </div> -->
                    </div>
                    <div style="height: 15px;"></div>
                    <div>
                        <div>现场照片（图2）</div>
                        <div style="height: 15rpx;"></div>
                        <!-- <div class="borders"> -->
                        <u-upload :capture="['camera']" :fileList="fileList2" @afterRead="afterReads"
                            @delete="deletePics" name="2" multiple :maxCount="1" width="150" height="150">
                        </u-upload>
                        <!-- </div> -->
                    </div>
                    <div style="height: 15px;"></div>
                    <div class="button-footer" @click="saves">提交</div>
                </div>

                <div style="height: 15px;"></div>
                <div class="lookBtn" v-if="flag == '进行中任务'" @click="taskDetail(item)">查看</div>
            </div>
            <div class="border-content">
                <div style="height: 10rpx;"></div>
                <!-- 表单 -->
                <!-- <div style="color: #718778;"> -->
                    <!-- <div class="form-flex">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">日期</div>
                        <div class="borders">
                            <div style="height: 5rpx;"></div>
                            {{ date }}
                            <div style="height: 5rpx;"></div>

                        </div>
                    </div> -->
                    <!-- <div style="height: 10px;"></div>
                    <div class="form-flex">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">时间</div>
                        <div class="borders">
                            <div style="height: 5rpx;"></div>
                            23:24
                            <div style="height: 5rpx;"></div>
                        </div>
                    </div> -->
                    <!-- <div style="height: 10px;"></div> -->
                    <!-- <div class="form-flex">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">收运车</div>
                        <div class="borders">
                            <div style="height: 5rpx;"></div>
                            {{ licenseNumber }}
                            <div style="height: 5rpx;"></div>
                        </div>
                    </div> -->
                    <!-- <div style="height: 10px;"></div> -->
                    <!-- <div class="form-flex">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">收运点</div>
                        <div class="borders">
                            <div style="height: 5rpx;"></div>
                            <!-- <picker @change="(event) => bindPickerChange(event)" :value="index" :range="arr"> -->
                    <!-- <input v-model="farmName" type="text" disabled>
                        
                            <div style="height: 5rpx;"></div>
                        </div>
                    </div>  -->
                    <!-- <div style="height: 10px;"></div> -->
                    <!-- <div class="form-flex">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">预计收集</div>
                        <div style="display: flex;align-items: center;width: 70%;">
                            <div class="borders-min" style="width: 66%;">
                                <div style="height: 5rpx;"></div>
                                {{ vehicleOrganicType }}
                                <div style="height: 5rpx;"></div>
                            </div>
                            <div style="width: 5px;"></div>
                            <div class="borders-min" style="width: 30%;">
                                <div style="height: 5rpx;"></div>
                                <input type="number" placeholder-class="holder-class" placeholder="请输入"
                                    v-model="estimatedWeight">
                                <div style="height: 5rpx;"></div>
                            </div>
                            <div style="width: 20%;text-align: center;">吨</div>
                        </div>
                    </div> -->
                    <!-- <div style="height: 10px;"></div> -->
                    <!-- <div class="form-flex">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">检测浓度</div>
                        <div style="display: flex;align-items: center;width: 70%;">
                            <div class="borders-min" style="width: 60%;">
                                <div style="height: 5rpx;"></div>
                                <input type="text" placeholder-class="holder-class" v-model="organicConcentration"
                                    placeholder="请输入浓度">
                                <div style="height: 5rpx;"></div>
                            </div>
                            <div style="width: 5px;"></div>
                            <div class="borders-min" style="width: 40%;">
                                <div style="height: 5rpx;"></div>
                                <input v-model="ts" disabled type="number">
                                <div style="height: 5rpx;"></div>
                            </div>
                        </div>
                    </div> -->

                    <div style="height: 10px;"></div>
                   
                <!-- </div> -->
                <!-- 
                <div>
                    <div style="width: 30%;color: #1A512C;font-weight: 500;">现场照片</div>
                    <div style="height: 5px;"></div>
                    <div style="display: flex;align-items: center;justify-content: space-between;">
                        <div>
                            <u-upload :capture="['camera']" :fileList="fileList1" @afterRead="afterRead"
                                @delete="deletePic" name="1" multiple :maxCount="1" width="150" height="150">
                                <image src="https://28-1325662301.cos.ap-shanghai.myqcloud.com/static%2Fupload.jpg"
                                    mode="widthFix" style="width: 150px;height: 150px;"></image>
                            </u-upload>
                        </div>
                        <div>
                            <u-upload :capture="['camera']" :fileList="fileList2" @afterRead="afterReads"
                                @delete="deletePics" name="2" multiple :maxCount="1" width="150" height="150">
                                <image src="https://28-1325662301.cos.ap-shanghai.myqcloud.com/static%2Fupload.jpg"
                                    mode="widthFix" style="width: 150px;height: 150px;"></image>
                            </u-upload>
                        </div>
                    </div>
                </div> -->
                <!-- 按钮 -->
                <div style="height: 10px;"></div>
                <div class="footer">
                    <!-- <div class="button-footer" @click="cancel">取消</div> -->
                </div>
            </div>
        </div>
        <!-- 遮罩层 -->
        <u-overlay :show="show" @click="show = false">
            <view class="warp">
                <view class="rect" @tap.stop>
                    <div style="height: 20px;"></div>
                    <div style="text-align: center;">出厂过磅重量</div>
                    <div style="height: 30px;"></div>
                    <div style="display: flex;justify-content: center;">
                        <input v-model="leaveWeight" style="text-align: center;" type="numbrt" placeholder="请输入出厂过磅重量">
                    </div>
                    <div style="height: 20px;"></div>
                    <div style="height: 20px;"></div>
                    <div class="yesFillOut" @click="yesFillOut">确认</div>
                    <div style="height: 20px;"></div>
                </view>
            </view>
        </u-overlay>
    </view>
</template>
<script>
import { fillSave, farmLists, cancelStop, fillInLeaveWeight } from '../api/api';
import request from '../../common/request';
export default {
    data() {
        const currentDate = this.getDate({
            format: true
        })
        return {
            date: currentDate,
            dates: new Date().toISOString(),//现在时间
            licenseNumber: '',
            organicConcentration: '',
            ts: 'TS',
            organicType: "",
            estimatedWeight: '',
            farmId: '',
            workOrderId: '',
            workOrderDetailId: '',
            farmName: '',
            arr: [],
            findArr: [],
            fileList1: [],
            fileList2: [],
            img1: '',
            img2: '',
            base: '',
            request: request,
            state: '',
            vehicleId: '',
            id: '',
            show: false,
            leaveWeight: ''
        }
    },
    methods: {
        yesFillOut() {
            if (this.leaveWeight == '') {
                uni.showToast({
                    title: '输入完整后提交',
                    icon: 'none'
                })
            } else {
                fillInLeaveWeight({
                    leaveWeight: this.leaveWeight,
                    id: this.workOrderId
                }).then(res => {
                    console.log(res.data);
                    if (res.data.code == 200) {
                        uni.showToast({
                            title: '操作成功',
                            icon: 'none'
                        })
                        this.show = false;
                        // setTimeout(()=>{
                        //     uni.navigateBack({
                        //         delta:1
                        //     })
                        // },1000)
                    } else {
                        uni.showToast({
                            title: '操作失败',
                            icon: 'none'
                        })
                    }
                })
            }

        },
        bindPickerChange(e) {
            const value = e.detail.value;
            console.log(value);
            console.log(this.findArr[value]);
            const obj = this.findArr[value];
            this.farmName = obj.farmName;
            this.farmId = obj.farmId;
            this.workOrderDetailId = obj.id;
            this.workOrderId = obj.workOrderId;
        },
        // 返回
        cancel() {
            uni.navigateBack({ delta: 1 })
        },
        bindDateChange: function (e) { //选择日期
            this.date = e.detail.value
            console.log('date', this.date)
        },
        getDate(type) { //年月日
            const date = new Date();
            // const date = new Date();
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();

            if (type === 'start') {
                year = year - 60;
            } else if (type === 'end') {
                year = year + 2;
            }
            month = month > 9 ? month : '0' + month;
            day = day > 9 ? day : '0' + day;
            return `${year}-${month}-${day}`;
        },
        dateFormat(time) {
            let date = new Date(time);
            let year = date.getFullYear();
            let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
            let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
            let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
            let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
            let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
            // 拼接
            return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
        },
        deletePic(event) {
            this[`fileList${event.name}`].splice(event.index, 1)
        },
        deletePics(event) {
            this[`fileList${event.name}`].splice(event.index, 1)
        },
        // 新增图片
        async afterRead(event) {
            console.log(event);
            let lists = [].concat(event.file)
            let fileListLen = this[`fileList${event.name}`].length
            lists.map((item) => {
                this[`fileList${event.name}`].push({
                    ...item,
                    status: 'uploading',
                    message: '上传中'
                })
            })
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i].url)
                let item = this[`fileList${event.name}`][fileListLen]
                this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
                    status: 'success',
                    message: '',
                    url: result
                }))
                fileListLen++
            }
        },
        async afterReads(event) {
            console.log(event);
            let lists = [].concat(event.file)
            let fileListLen = this[`fileList${event.name}`].length
            lists.map((item) => {
                this[`fileList${event.name}`].push({
                    ...item,
                    status: 'uploading',
                    message: '上传中'
                })
            })
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromises(lists[i].url)
                let item = this[`fileList${event.name}`][fileListLen]
                this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
                    status: 'success',
                    message: '',
                    url: result
                }))
                fileListLen++
            }
        },
        uploadFilePromise(url) {
            return new Promise((resolve, reject) => {
                let a = uni.uploadFile({
                    url: `${this.base}/file-upload/single`,
                    filePath: url,
                    name: 'file',
                    formData: {
                        'type': 'faultPhoto'
                    },
                    header: {
                        Authorization: uni.getStorageSync('token')
                    },
                    success: (res) => {
                        const data = JSON.parse(res.data)
                        console.log(data);
                        this.img1 = data.data;
                        resolve(res.data.data)
                    }
                });
            })
        },
        uploadFilePromises(url) {
            return new Promise((resolve, reject) => {
                let a = uni.uploadFile({
                    url: `${this.base}/file-upload/single`,
                    filePath: url,
                    name: 'file',
                    formData: {
                        'type': 'faultPhoto'
                    },
                    header: {
                        Authorization: uni.getStorageSync('token')
                    },
                    success: (res) => {
                        const data = JSON.parse(res.data)
                        console.log(data, 'data2');
                        this.img2 = data.data;
                        resolve(res.data.data)
                    }
                });
            })
        },
        //填报
        saves() {
            let t = this;
            if (t.state == 6) {
                uni.showModal({
                    title: '提示',
                    content: '当前车辆保停中,是否取消报停',
                    success: function (res) {
                        if (res.confirm) {
                            console.log('用户点击确定');
                            cancelStop({
                                vehicleId: t.vehicleId,
                                id: t.id
                            }).then(res => {
                                console.log(res.data, 'res.data');
                                if (res.data.code == 200) {
                                    uni.showToast({
                                        title: res.data.msg,
                                        icon: 'none'
                                    })
                                    t.fills();
                                    uni.removeStorageSync('state')
                                } else {
                                    uni.showToast({
                                        title: res.data.msg,
                                        icon: 'none',
                                        duration: 3000
                                    })
                                }
                            })
                        } else if (res.cancel) {
                            console.log('用户点击取消');
                        }
                    }
                });
            } else {
                if (t.organicConcentration == '' || t.estimatedWeight == '') {
                    uni.showToast({ title: '请输入完整', icon: 'none' })
                } else if (t.img1 == '' || t.img2 == '') {
                    uni.showToast({ title: '上传图片后提交', icon: 'none' })
                } else {
                    console.log(t.workOrderId);

                    let combinedString = `${t.img1},${t.img2}`;
                    fillSave({
                        dateTime: t.dateFormat(t.dates),
                        licenseNumber: t.licenseNumber,
                        farmId: t.farmId,
                        organicType: t.vehicleOrganicType,
                        actualWeight: t.estimatedWeight,
                        organicConcentration: t.organicConcentration,
                        ts: t.ts,
                        workOrderId: t.workOrderId,
                        workOrderDetailId: t.workOrderDetailId,
                        scenePhoto: combinedString
                    }).then(res => {
                        console.log(res, 'res');
                        if (res.data.code == 200) {
                            uni.showToast({
                                title: res.data.msg,
                                icon: 'success'
                            })
                            // uni.getStorageSync('fillWork', false);
                            t.clear();
                            setTimeout(() => {
                                uni.removeStorageSync('fillWork');
                                uni.navigateBack({ delta: 1 })
                            }, 1000)
                        } else {
                            uni.showToast({
                                title: res.data.msg,
                                icon: 'none'
                            })
                            setTimeout(() => {
                                if (res.data.msg == "未找到出厂过磅信息") {
                                    this.show = true;
                                }
                            }, 1000)
                        }
                    })
                }
            }


        },
        clear() {
            this.farmId = '';
            this.organicConcentration = '';
        },
        fills() {
            //     farmLists({ workOrderState: '1',workOrderDetailState:0}).then(res => {
            //     console.log(res.data, 'res');
            //     this.state = res.data.data[0].workOrder.workOrderState;
            //     this.id = res.data.data[0].workOrder.id;
            //     this.vehicleId = res.data.data[0].workOrder.vehicleId;
            //     this.licenseNumber = res.data.data[0].workOrder.licenseNumber;
            //     this.vehicleOrganicType = res.data.data[0].workOrder.vehicleOrganicType;
            //     // this.estimatedWeight = res.data.data[0].workOrder.estimatedWeight;
            //     this.arr = res.data.data[0].workAndFarmVOList.map((item) => item.farmName);
            //     // this.findArr = res.data.data[0].workAndFarmVOList;
            //     this.farmName = res.data.data[0].workAndFarmVOList[0].farmName;
            //     this.farmId = res.data.data[0].workAndFarmVOList[0].farmId;
            //     this.workOrderDetailId = res.data.data[0].workAndFarmVOList[0].id;
            //     this.workOrderId = res.data.data[0].workAndFarmVOList[0].workOrderId;
            //     console.log(this.vehicleId,this.id,'1234567890');
            // })
            let obj = uni.getStorageSync('fillWork');
            this.state = obj.workOrderState;
            // this.id = obj.id;
            this.vehicleId = obj.vehicleId;
            this.licenseNumber = obj.licenseNumber;
            this.vehicleOrganicType = obj.organicType;
            // this.estimatedWeight = obj.estimatedWeight;
            // this.arr = res.data.data[0].workAndFarmVOList.map((item) => item.farmName);
            // this.findArr = res.data.data[0].workAndFarmVOList;
            this.farmName = obj.farmName;
            this.farmId = obj.farmId;
            this.workOrderDetailId = obj.id;
            this.workOrderId = obj.workOrderId;
        }
    },
    computed: {
        startDate() {
            return this.getDate('start');
        },
        endDate() {
            return this.getDate('end');
        }
    },
    onShow() {
        let _this = this;
        setInterval(function () {
            _this.dates = Date.parse(new Date());
        }, 1000);
        // 
        this.fills()
        this.base = this.request.config.baseURL;
    }
}
</script>
<style lang="scss">
.container {
    background: #f3f3f3;

    .border {
        background: #f3f3f3;
        height: 100vh;
        overflow-y: scroll;

        .border-content {
            width: 90%;
            margin-left: 5%;
        }
    }
}

.top-line {
    display: flex;
    align-items: center;
}

.line {
    background: #1A512C;
    width: 7rpx;
    height: 35rpx;
}

.form-flex {
    display: flex;
    align-items: center;
    width: 100%;
}

.borders {
    border: 1px solid #000000;
    border-radius: 5px;
    text-align: center;
}

.footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.button-footer {
    width: 90%;
    margin-left: 5%;
    height: 50px;
    background: #000000;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 18px;
    font-weight: 500;
    border-radius: 10px;
}

.warp {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    font-size: 17px;
}

.rect {
    width: 90vw;
    // height: 120px;
    border-radius: 5px;
    background-color: #fff;
}

.yesFillOut {
    width: 90%;
    margin-left: 5%;
    height: 35px;
    border-radius: 5px;
    background: #1A512C;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
}

.card {
    width: 95%;
    margin-left: 2.5%;
    margin-top: 10px;
    border-radius: 10px;
    background: #ffffff;

    .card-top {
        font-size: 14px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 90%;
        margin-left: 5%;
    }
}

.newFlex {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 90%;
    margin-left: 5%;
}
</style>